<?php
declare(strict_types=1);

namespace LowCode\Traits\Vue;

use Illuminate\Support\Collection;

trait HasRef
{
    /**
     * @param string $refKey
     * @param mixed|null $refValue
     * @return $this
     */
    public function ref(string $refKey, string|int|float|bool|array $refValue = null): static
    {
        if (is_array($refValue)){
            $refValue = json_encode($refValue, JSON_UNESCAPED_UNICODE);
            $html = "const $refKey = ref($refValue)";
        }else if (is_numeric($refValue)||is_bool($refValue)){
            $html = "const $refKey = ref($refValue)";
        }else{
            $html = "const $refKey = ref(\"$refValue\")";
        }
        $this->builder->ref->put($refKey, $html);
        $this->variables->add($refKey);
        return $this;
    }


    /**
     * @param string $refKey
     * @return $this
     */
    public function removeRef(string $refKey): static
    {
        if ($this->builder->ref->has($refKey)){
            $this->builder->ref->forget($refKey);
            $key = $this->variables->search($refKey);
            $variables = $this->variables->forget($key)->values()->all();
            $this->variables = Collection::make($variables);
        }
        return $this;
    }

    protected function getRefHtml(): string
    {
        if ($this->builder->ref->isNotEmpty()){
            $this->addVueImport("ref");
        }
        $values = $this->builder->ref->all();
        return $this->implode($values);
    }
}
